<template>
  <div class="store-manage-container">
    <!-- 顶部导航栏 -->
    <header class="top-nav">
      <div class="logo">店铺管理系统</div>
      <button class="logout-btn" @click="handleLogout">
        <i class="fa fa-sign-out"></i> 退出登录
      </button>
    </header>

    <!-- 功能导航：仅保留店铺管理、统计，移除菜品管理 -->
    <nav class="function-nav">
      <button 
        class="function-btn" 
        :class="{ active: activeTab === 'storeManage' }"
        @click="activeTab = 'storeManage'"
      >
        <i class="fa fa-shopping-bag"></i> 店铺管理
      </button>
      <button 
        class="function-btn" 
        :class="{ active: activeTab === 'statistics' }"
        @click="activeTab = 'statistics'"
      >
        <i class="fa fa-bar-chart"></i> 统计功能
      </button>
    </nav>

    <!-- 主内容区 -->
    <main class="main-content">
      <!-- 操作栏 - 返回按钮 -->
      <div class="action-bar">
        <button class="back-btn" @click="goBack">
          <i class="fa fa-arrow-left"></i> 返回上一页
        </button>
      </div>

      <!-- 加载状态 -->
      <div v-if="isLoading" class="loading">
        <i class="fa fa-circle-o-notch fa-spin"></i> 加载中...
      </div>

      <!-- 错误提示 -->
      <div v-if="errorMessage" class="error-message">
        <i class="fa fa-exclamation-circle"></i> {{ errorMessage }}
        <button class="close-btn" @click="errorMessage = ''">
          <i class="fa fa-times"></i>
        </button>
      </div>

      <!-- 店铺管理内容 -->
      <div v-if="activeTab === 'storeManage' && !isLoading && !errorMessage">
        <div class="section-header">
          <h2 class="section-title">店铺管理</h2>
          <!-- <button class="add-btn" @click="showCreateModal = true">
            <i class="fa fa-plus"></i> 创建新店铺
          </button> -->
        </div>

        <!-- 店铺列表 -->
        <div class="store-list">
          <div v-if="stores.length === 0" class="empty-state">
            <i class="fa fa-store"></i>
            <p>暂无店铺数据</p>
            <button class="create-first-btn" @click="handleShowCreateModel">
              创建您的第一个店铺
            </button>
          </div>

          <!-- 店铺卡片 -->
          <div 
            class="store-card" 
            v-for="store in stores" 
            :key="store.id"
          >
            <div class="store-image">
              <img 
                :src="store.image ? `/${store.image}` : defaultStoreImage" 
                alt="店铺图片" 
                class="store-img"
              >
            </div>
            
            <div class="store-info">
              <h3 class="store-name">{{ store.name }}</h3>
              <p><strong>店主：</strong>{{ store.user_name }}</p>
              <p><strong>地址：</strong><span class="text-ellipsis">{{ store.location || '未设置' }}</span></p>
              <p>
                <strong>状态：</strong>
                <span 
                  :class="store.status === 1 ? 'status-open' : 'status-closed'"
                >
                  {{ store.status_display }}
                </span>
              </p>
            </div>

            <!-- 店铺操作按钮：重点修复菜品管理跳转 -->
            <div class="store-actions">
              <button 
                class="action-btn status-btn"
                :class="store.status === 1 ? 'status-close' : 'status-open'"
                @click="handleStatusChange(store.id, store.status)"
              >
                {{ store.status === 1 ? '暂停营业' : '开始营业' }}
              </button>
              <button class="action-btn edit-btn" @click="handleEditStore(store)">
                <i class="fa fa-edit"></i> 编辑
              </button>
              <!-- 核心：调用正确的跳转方法 -->
              <button class="action-btn add-dish-btn" @click="handleGoToCommodityManage(store.id)">
                <i class="fa fa-list"></i> 菜品管理
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 统计功能（占位） -->
      <div v-if="activeTab === 'statistics' && !isLoading && !errorMessage" class="placeholder-section">
        <h2 class="section-title">统计功能</h2>
           <!-- <OrderStatics /> -->
      </div>

      <!-- 创建/编辑店铺弹窗 -->
      <div v-if="showStoreModal" class="modal-overlay">
        <div class="modal">
          <div class="modal-header">
            <h3>{{ isEditing ? '编辑店铺' : '创建新店铺' }}</h3>
            <button class="close-modal" @click="closeStoreModal">
              <i class="fa fa-times"></i>
            </button>
          </div>

          <form @submit.prevent="isEditing ? updateStore() : createStore()" class="modal-form">
            <div class="form-group">
              <label for="storeName">店铺名称 <span class="required">*</span></label>
              <input
                type="text"
                id="storeName"
                v-model="currentStore.name"
                required
                placeholder="请输入店铺名称"
                class="form-input"
              >
            </div>

            <div class="form-group">
              <label for="storeLocation">店铺地址 <span class="required">*</span></label>
              <input
                type="text"
                id="storeLocation"
                v-model="currentStore.location"
                required
                placeholder="请输入店铺地址"
                class="form-input"
              >
            </div>

            <div class="form-group">
              <label for="storeImage">店铺图片</label>
              <input
                type="file"
                id="storeImage"
                accept="image/jpeg, image/png"
                @change="handleImageUpload"
                class="file-input"
              >
              <div v-if="previewImage" class="image-preview">
                <img :src="previewImage" alt="预览图" class="preview-img">
              </div>
            </div>

            <div class="form-group">
              <label for="storeStatus">状态</label>
              <select 
                id="storeStatus" 
                v-model="currentStore.status" 
                class="form-select"
              >
                <option value="1">营业中</option>
                <option value="2">休息中</option>
              </select>
            </div>

            <div class="modal-footer">
              <button type="button" class="cancel-btn" @click="closeStoreModal">
                取消
              </button>
              <button 
                type="submit" 
                class="submit-btn"
                :disabled="isSubmitting"
              >
                <span v-if="isSubmitting">{{ isEditing ? '更新中...' : '创建中...' }}</span>
                <span v-else>{{ isEditing ? '更新店铺' : '创建店铺' }}</span>
              </button>
            </div>
          </form>
        </div>
      </div>

      <!-- 状态修改确认弹窗 -->
      <div v-if="showStatusModal" class="modal-overlay">
        <div class="modal confirm-modal">
          <div class="modal-header">
            <h3>确认修改状态</h3>
            <button class="close-modal" @click="showStatusModal = false">
              <i class="fa fa-times"></i>
            </button>
          </div>

          <div class="modal-body">
            <p>您确定要将店铺状态修改为 <strong>{{ statusChangeTarget }}</strong> 吗？</p>
          </div>

          <div class="modal-footer">
            <button type="button" class="cancel-btn" @click="showStatusModal = false">
              取消
            </button>
            <button 
              type="button" 
              class="submit-btn"
              @click="confirmStatusChange"
              :disabled="isProcessing"
            >
              <span v-if="isProcessing">处理中...</span>
              <span v-else>确认</span>
            </button>
          </div>
        </div>
      </div>
    </main>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, toRefs } from 'vue';
import { cloneDeep } from 'lodash';
import { useRouter } from 'vue-router';
import axios from 'axios';

// 路由实例（关键：确保路由对象正确创建）
const router = useRouter();

// 状态管理
const state = reactive({
  isLoading: true,
  isSubmitting: false,
  isProcessing: false,
  errorMessage: '',
  successMessage: '',
  activeTab: 'storeManage',
  stores: [],
  currentStore: {
    id: null,
    name: '',
    location: '',
    image: null,
    status: 1 // 1=营业中，2=休息中
  },
  showStoreModal: false,
  showStatusModal: false,
  isEditing: false,
  currentStoreId: null,
  currentStoreStatus: 1,
  statusChangeTarget: '',
  previewImage: '',
  defaultStoreImage: 'https://picsum.photos/id/292/300/200'
});

const { 
  isLoading, isSubmitting, isProcessing, errorMessage,
  activeTab, stores, currentStore, showStoreModal,
  showStatusModal, isEditing, currentStoreId,
  currentStoreStatus, statusChangeTarget, previewImage,
  defaultStoreImage
} = toRefs(state);

// 返回上一页
const goBack = () => {
  router.back();
};

// 获取店铺列表
const fetchStores = async () => {
  try {
    isLoading.value = true;
    const response = await axios.get('/user/store/info/');
    stores.value = response.data;
  } catch (err) {
    errorMessage.value = err.response?.data?.message || '获取店铺列表失败';
    console.error('获取店铺列表失败:', err);
  } finally {
    isLoading.value = false;
  }
};

// 图片上传预览
const handleImageUpload = (e) => {
  const file = e.target.files[0];
  if (!file) return;
  
  if (!['image/jpeg', 'image/png'].includes(file.type)) {
    errorMessage.value = '请上传JPG或PNG格式的图片';
    return;
  }
  
  currentStore.value.image = file;
  const reader = new FileReader();
  reader.onload = (e) => {
    previewImage.value = e.target.result;
  };
  reader.readAsDataURL(file);
};

// 创建店铺
const createStore = async () => {
  try {
    isSubmitting.value = true;
    const formData = new FormData();
    formData.append('name', currentStore.value.name);
    formData.append('location', currentStore.value.location);
    formData.append('status', currentStore.value.status);
    if (currentStore.value.image) {
      formData.append('image', currentStore.value.image);
    }
    
    const response = await axios.post('/user/store/', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    });
    
    stores.value.push(response.data);
    closeStoreModal();
    errorMessage.value = '';
    alert('店铺创建成功');
  } catch (err) {
    errorMessage.value = err.response?.data?.message || '创建店铺失败';
    console.error('创建店铺失败:', err);
  } finally {
    isSubmitting.value = false;
  }
};

const handleShowCreateModel = () => {
  // 重置表单状态
  currentStore.value = {
    id: null,
    name: '',
    location: '',
    image: null,
    status: 1
  };
  previewImage.value = '';
  isEditing.value = false;
  // 显示弹窗
  showStoreModal.value = true;
  // 调试用，确认方法被调用
  console.log('创建店铺按钮被点击，弹窗状态已设置为:', showStoreModal.value);
};

// 更新店铺
const updateStore = async () => {
  try {
    isSubmitting.value = true;
    const formData = new FormData();
    formData.append('name', currentStore.value.name);
    formData.append('location', currentStore.value.location);
    formData.append('status', currentStore.value.status);
    if (currentStore.value.image) {
      formData.append('image', currentStore.value.image);
    }
    
    const response = await axios.put(
      `/user/store/${currentStore.value.id}/`, 
      formData, 
      { headers: { 'Content-Type': 'multipart/form-data' } }
    );
    
    const index = stores.value.findIndex(store => store.id === currentStore.value.id);
    if (index !== -1) {
      stores.value[index] = response.data;
    }
    closeStoreModal();
    alert('店铺更新成功');
  } catch (err) {
    errorMessage.value = err.response?.data?.message || '更新店铺失败';
    console.error('更新店铺失败:', err);
  } finally {
    isSubmitting.value = false;
  }
};

// 店铺状态修改
const handleStatusChange = (storeId, status) => {
  currentStoreId.value = storeId;
  currentStoreStatus.value = status;
  statusChangeTarget.value = status === 1 ? '休息中' : '营业中';
  showStatusModal.value = true;
};

// 确认状态修改
const confirmStatusChange = async () => {
  try {
    isProcessing.value = true;
    const targetStatus = currentStoreStatus.value === 1 ? 2 : 1;
    await axios.put(`/user/store/${currentStoreId.value}/change/`, { status: targetStatus });
    
    const index = stores.value.findIndex(store => store.id === currentStoreId.value);
    if (index !== -1) {
      stores.value[index].status = targetStatus;
      stores.value[index].status_display = targetStatus === 1 ? '营业中' : '休息中';
    }
    
    showStatusModal.value = false;
    alert('店铺状态修改成功');
  } catch (err) {
    errorMessage.value = err.response?.data?.message || '修改店铺状态失败';
    console.error('修改状态失败:', err);
  } finally {
    isProcessing.value = false;
  }
};

// 编辑店铺
const handleEditStore = (store) => {
  currentStore.value = cloneDeep(store);
  isEditing.value = true;
  showStoreModal.value = true;
  previewImage.value = store.image ? `/${store.image}` : '';
};

// 关闭店铺弹窗
const closeStoreModal = () => {
  showStoreModal.value = false;
  isEditing.value = false;
  previewImage.value = '';
  currentStore.value = {
    id: null,
    name: '',
    location: '',
    image: null,
    status: 1
  };
};

// 核心修复：菜品管理跳转方法（替换原无效的handleAddDish）
const handleGoToCommodityManage = (storeId) => {
  console.log(`跳转至店铺ID: ${storeId} 的菜品管理页面`);
  // 两种跳转方式任选其一（推荐第一种，与路由name对应）
  router.push({
    name: 'Commodity', // 必须与路由配置中的"name"字段一致
    params: { storeId: storeId } // 传递店铺ID参数
  });
  // 或直接用路径跳转：router.push(`/commodity/${storeId}`)
};

// 退出登录
const handleLogout = () => {
  localStorage.removeItem('token');
  router.push('/login');
};

// 页面加载时获取店铺数据
onMounted(() => {
  fetchStores();
});
</script>

<style scoped>
/* 样式保持不变 */
.store-manage-container {
  min-height: 100vh;
  background-color: #fff;
  color: #333;
  display: flex;
  flex-direction: column;
}

.top-nav {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 30px;
  background-color: #ff7a5a;
  color: white;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.logo {
  font-size: 20px;
  font-weight: bold;
}

.logout-btn {
  background-color: white;
  color: #333;
  border: none;
  padding: 8px 15px;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 5px;
  transition: all 0.3s;
}

.logout-btn:hover {
  background-color: #f8f9fa;
  transform: translateY(-2px);
}

.function-nav {
  display: flex;
  background-color: #fff5f5;
  border-bottom: 1px solid #ffe0e0;
}

.function-btn {
  padding: 15px 30px;
  background: none;
  border: none;
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 16px;
  color: #333;
  cursor: pointer;
  transition: all 0.3s;
}

.function-btn:hover {
  background-color: #ffe8e8;
}

.function-btn.active {
  background-color: #ffd166;
  color: #333;
  font-weight: bold;
  border-bottom: 3px solid #ff7a5a;
}

.main-content {
  flex: 1;
  padding: 30px;
  overflow-y: auto;
}

.action-bar {
  margin-bottom: 20px;
}

.back-btn {
  background-color: #f8f9fa;
  color: #333;
  border: 1px solid #ddd;
  padding: 8px 15px;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s;
  font-size: 14px;
}

.back-btn:hover {
  background-color: #e9ecef;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-title {
  color: #ff7a5a;
  font-size: 22px;
  margin: 0;
}

.add-btn {
  background-color: #ff7a5a;
  color: white;
  border: none;
  padding: 8px 15px;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s;
}

.add-btn:hover {
  background-color: #e66a4c;
  transform: translateY(-2px);
}

.store-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(380px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.store-card {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(255,122,90,0.1);
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 15px;
  transition: transform 0.3s;
  height: 100%;
}

.store-card:hover {
  transform: translateY(-5px);
}

.store-image {
  width: 100%;
  height: 200px;
  border-radius: 4px;
  overflow: hidden;
}

.store-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.5s;
}

.store-card:hover .store-img {
  transform: scale(1.05);
}

.store-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.store-name {
  margin: 0;
  color: #333;
  font-size: 18px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.store-info p {
  margin: 0;
  font-size: 14px;
  display: flex;
  gap: 5px;
}

.store-info p strong {
  white-space: nowrap;
}

.text-ellipsis {
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.status-open {
  color: #28a745;
  background-color: #f0fff4;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 13px;
}

.status-closed {
  color: #dc3545;
  background-color: #fff5f5;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 13px;
}

.store-actions {
  display: flex;
  gap: 10px;
  margin-top: auto;
  flex-wrap: wrap;
}

.action-btn {
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 14px;
  border: none;
  flex: 1;
  min-width: 100px;
}

.status-btn {
  color: white;
}

.status-close {
  background-color: #dc3545;
}

.status-close:hover {
  background-color: #c82333;
}

.edit-btn {
  background-color: #ffd166;
  color: #333;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
}

.edit-btn:hover {
  background-color: #ffc433;
}

.add-dish-btn {
  background-color: #ff7a5a;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
}

.add-dish-btn:hover {
  background-color: #e66a4c;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  background-color: #fff5f5;
  border-radius: 8px;
  color: #888;
}

.empty-state i {
  font-size: 50px;
  margin-bottom: 20px;
  color: #ffb3b3;
}

.create-first-btn {
  margin-top: 20px;
  background-color: #ff7a5a;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.create-first-btn:hover {
  background-color: #e66a4c;
}

.placeholder-section {
  padding: 50px 20px;
}

.placeholder-content {
  text-align: center;
  padding: 80px 20px;
  background-color: #fff5f5;
  border-radius: 8px;
  color: #888;
}

.placeholder-content i {
  font-size: 60px;
  margin-bottom: 20px;
  color: #ffb3b3;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal {
  background-color: white;
  border-radius: 8px;
  width: 100%;
  max-width: 500px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
}

.confirm-modal {
  max-width: 400px;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
}

.modal-header h3 {
  margin: 0;
  color: #333;
}

.close-modal {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #888;
}

.modal-form {
  padding: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: #555;
  font-weight: 500;
}

.required {
  color: #dc3545;
}

.form-input, .form-select {
  width: 100%;
  padding: 10px 15px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
  transition: border-color 0.3s;
}

.form-input:focus, .form-select:focus {
  outline: none;
  border-color: #ff7a5a;
}

.file-input {
  padding: 5px;
}

.image-preview {
  margin-top: 10px;
}

.preview-img {
  max-width: 200px;
  max-height: 150px;
  border-radius: 4px;
  border: 1px solid #eee;
}

.modal-body {
  padding: 20px;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 15px 20px;
  border-top: 1px solid #eee;
}

.cancel-btn {
  padding: 8px 15px;
  background-color: #f8f9fa;
  color: #333;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.cancel-btn:hover {
  background-color: #e9ecef;
}

.submit-btn {
  padding: 8px 15px;
  background-color: #ff7a5a;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.submit-btn:hover {
  background-color: #e66a4c;
}

.submit-btn:disabled {
  background-color: #ffb3b3;
  cursor: not-allowed;
}

.loading {
  text-align: center;
  padding: 50px;
  color: #ff7a5a;
  font-size: 18px;
}

.error-message {
  background-color: #ffebee;
  color: #b71c1c;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 10px;
}

.close-btn {
  background: none;
  border: none;
  color: #b71c1c;
  cursor: pointer;
  font-size: 16px;
}

@media (max-width: 768px) {
  .function-nav {
    overflow-x: auto;
  }
  
  .function-btn {
    padding: 15px 20px;
    flex-shrink: 0;
  }
  
  .store-list {
    grid-template-columns: 1fr;
  }
  
  .store-actions {
    flex-direction: column;
  }
  
  .action-btn {
    width: 100%;
    min-width: auto;
  }
}
</style>
    